#include "../t_thread.h"
#include <iostream>
#include <chrono>
#include <vector>

// 基本的启动、停止和状态检查
void basic_usage_example() {
    std::cout << "--- Basic Usage Example ---";
    THREAD thread;

    std::cout << "Thread state before start: " << static_cast<int>(thread.get_state()) << " (Ready)" << std::endl;
    // 启动线程
    thread.start("WorkerThread1", [&]() {
        int counter = 0;
        // 线程主循环，定期检查是否需要停止
        while (!thread.is_stop_requested()) {
            std::cout << "Thread " << std::this_thread::get_id() << "  is working... counter = " << counter++ << std::endl;
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }
        std::cout << "Thread " << std::this_thread::get_id() << "  received stop request and is exiting." << std::endl;
    });

    std::cout << "Thread state after start: " << static_cast<int>(thread.get_state()) << " (Running)\n";
    std::cout << "Thread ID: " << thread.get_id() << std::endl;

    // 让线程运行3秒
    std::this_thread::sleep_for(std::chrono::seconds(3));

    // 请求停止线程
    std::cout << "Requesting thread to stop...\n";
    thread.request_stop();

    // 等待线程结束
    thread.join();
    std::cout << "Thread joined.\n";
    std::cout << "Thread state after join: " << static_cast<int>(thread.get_state()) << " (Stopped)\n";
}

// 线程控制（传递数据）和超时控制
void advanced_control_example() {
    std::cout << "\n--- Advanced Control & Timeout Example ---\n";
    T_THREAD::Thread thread;

    std::vector<int> task_queue; // 模拟任务队列，作为共享数据

    thread.start("AdvancedWorker", [&]() {
        std::cout << "Advanced thread started, waiting for tasks...\n";
        while (!thread.is_stop_requested())
        {
            int task_data = -1;
            {
                // 使用unique_lock来管理互斥锁
                std::unique_lock lock(thread.get_mutex());
                
                // 使用wait_for实现超时等待
                // 等待1秒，如果期间没有被唤醒（没有新任务），或者被请求停止，则继续循环
                if (thread.get_cv().wait_for(lock, std::chrono::seconds(1), [&]() {
                    return thread.is_stop_requested() || !task_queue.empty();
                }))
                {
                    // 被唤醒
                    if (thread.is_stop_requested())
                        break; // 如果是停止请求，则退出
                    if (task_queue.empty())
                        continue;

                    task_data = task_queue.front();
                    task_queue.erase(task_queue.begin());
                    std::cout << "Processed task: " << task_data << std::endl;
                }
                else
                {
                    // 等待超时
                    std::cout << "Waited for 1 second, no new task.\n";
                }
            }
        }
        std::cout << "Advanced thread is exiting.\n";
    });

    // 主线程向工作线程“传递参数”（发送任务）
    for (int i = 0; i < 3; ++i) {
        std::this_thread::sleep_for(std::chrono::seconds(2));
        {
            std::lock_guard lock(thread.get_mutex());
            std::cout << "Main thread posting task: " << i << std::endl;
            task_queue.push_back(i);
        }
        thread.get_cv().notify_one(); // 唤醒工作线程
    }

    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "Main thread requesting stop.\n";
    thread.request_stop();
    thread.get_cv().notify_all(); // 确保线程从等待中唤醒以检查停止标志
    thread.join();
    std::cout << "Advanced thread joined.\n";
}

int main() {
    basic_usage_example();
    advanced_control_example();
    return 0;
}